package service

import (
	"context"
	"log"
	"regexp"
	"time"

	pb "customer/api/customer"
	verifyCode "customer/api/verifyCode"
	"customer/internal/data"

	"github.com/go-kratos/kratos/v2/transport/grpc"
)

type CustomerService struct {
	pb.UnimplementedCustomerServer
	customerData *data.CustomerData
}

func NewCustomerService(cd *data.CustomerData) *CustomerService {
	return &CustomerService{customerData: cd}
}

func (s *CustomerService) GetVerifyCode(ctx context.Context, req *pb.GetVarifyCodeReq) (
	*pb.GetVarifyCodeResp, error) {
	// 1 校验手机号
	pattern := `^1[3-9]\d{9}$`
	regPattern := regexp.MustCompile(pattern)
	if !regPattern.MatchString(req.Telephone) {
		return &pb.GetVarifyCodeResp{
			Code:    1,
			Message: "手机号格式不正确",
		}, nil
	}

	// 2 通过验证吗服务生产验证码 （涉及服务间通信）
	// 连接目标grpc服务器
	conn, err := grpc.DialInsecure(
		context.Background(),
		grpc.WithEndpoint("117.72.67.144:9000"),
	)
	if err != nil {
		return &pb.GetVarifyCodeResp{
			Code:    1,
			Message: "连接验证码服务失败",
		}, nil
	}
	defer func() {
		conn.Close()
	}()

	// 2 发送获取验证码请求
	Client := verifyCode.NewVerifyCodeClient(conn)
	resp, err := Client.GetVerifyCode(ctx, &verifyCode.GetVerifyCodeRequest{
		Length: 6,
		Type:   1,
	})
	if err != nil {
		return &pb.GetVarifyCodeResp{
			Code:    1,
			Message: "验证码获取错误",
		}, nil
	}

	// 3 临时使用redis存储
	// 3.1 连接redis
	// 用户名 密码 方式  // redis://[:password@]host:port/db-number[?option=value]
	const life = 60
	if err := s.customerData.SetVerifyCode(req.Telephone, resp.Code, life*time.Second); err != nil {
		log.Println(err)
		return &pb.GetVarifyCodeResp{
			Code:    1,
			Message: "验证码存储失败（Redis Set操作错误）",
		}, nil
	}

	return &pb.GetVarifyCodeResp{
		Code:           0,
		Data:           resp.Code,
		VerifyCodeTime: time.Now().Unix(),
		VerifyCodeLife: life,
	}, nil
}
